from mylearn.models import CosmeticsUser,CosmeticsHistory,CosmeticsGood
from rest_framework.response import Response
from rest_framework.views import APIView
from mylearn.mylearnser import MylearnCosGood,MylearnCosUser,MylearnCosHistory

class CosLogin(APIView):
    def get(self,request):
        name=request.GET.get('name')
        password=request.GET.get('password')
        user=CosmeticsUser.objects.filter(name=name,password=password).first()
        if user:
            return Response({'code':200,'msg':'登录成功','id':user.id,'name':user.name})
        else:
            return Response({'code': 400, 'msg': '登录失败'})


class CosShow(APIView):
    def get(self,request):
        goods=CosmeticsGood.objects.all()
        goods_ser=MylearnCosGood(goods,many=True)
        return Response({'data':goods_ser.data})


class CosPay(APIView):
    def get(self,request):
        id= request.GET.get('id')
        print(id)
        user = CosmeticsUser.objects.get(id=id)
        his=CosmeticsHistory.objects.filter(name=user.name).all()
        his_ser=MylearnCosHistory(his,many=True)
        return Response({'code':200,'data':his_ser.data})

    def post(self,request):
        id= request.POST.get('id')
        # 获取价格
        price= request.POST.get('price')
        cartstr= request.POST.get('cartstr')
        print(price)
        # user = CosmeticsUser.objects.get(pk=id)
        # # 修改资金
        # user.money=int(user.money)-price
        # user.save()
        #
        # # 更改库存
        # for i in eval(cartstr):
        #     good=CosmeticsGood.objects.filter(name=i['name']).first()
        #     good.num = int(good.num) - int(i['num'])
        #     good.save()
        # # 保存到记录表
        # his=CosmeticsHistory(name=user.name,goods=cartstr,money=price)
        # his.save()
        return Response({'code': 200, 'msg': '购买成功'})